const _ = require('lodash');
const async = require('async');
const LoopBackContext = require('loopback-context');
const services = require('../../services');
const enums = require('../../enums');

const commonService = services.common;
const eLancoService = services.eLanco;

module.exports = (req, res, callback) => {
  const context = LoopBackContext.getCurrentContext();
  // const form = context.get('form');
  // const flow = context.get('flow');
  const formDetail = context.get('formDetail');
  const formId = req.body.formId;
  const id = req.params.id;
  const formDetailData = req.body.formDetail;
  const employeeId = commonService.getEmployeeId();
  const { WfRunInstance: formDetailModel, WfRunFlowDetail: approvalDetailModel } = commonService.getModels();
  const getApprovalDetail = (next) => {
    commonService.getDetail(approvalDetailModel, {
      where: {
        formId,
        instanceId: id,
        approvalStep: formDetail.approvalStep,
        approvalStatus: enums.approvalStatus.pending,
        approverEmployeeId: employeeId,
      },
    }, next);
  };
  const saveApprovalDetail = (approvalDetail, next) => {
    if (!approvalDetail) return callback(commonService.getError(enums.errorCode.forbidden));
    approvalDetailModel.upsert({
      id: approvalDetail.id,
      approvalStatus: enums.approvalStatus.reject,
      comment: formDetailData.comment,
      approvalDate: new Date(),
    }, error => next(error));
  };
  const saveFormDetail = (next) => {
    let approvalStep = _.toNumber(formDetail.approvalStep);
    let formStatus = _.toNumber(formDetail.formStatus);
    formStatus = -formStatus - 1;
    approvalStep += 1;
    formDetailModel.upsert({
      id,
      formId,
      approvalStep,
      formStatus,
      formDetail: formDetailData,
    }, error => next(error));
  };
  const deleteApprovalList = (next) => {
    approvalDetailModel.updateAll({
      formId,
      instanceId: id,
      approvalStatus: enums.approvalStatus.pending,
    }, { deleted: true }, error => next(error));
  };
  const getFormDetail = (next) => {
    eLancoService.getFormDetailIncludeAll(formId, id, (error, formDetail) => {
      context.set('formDetail', formDetail);
      context.set('approvalList', formDetail.approvalList());
      next(error, formDetail);
    });
  };
  async.waterfall([getApprovalDetail, saveApprovalDetail, saveFormDetail, deleteApprovalList, getFormDetail], callback);
};
